package com.ttxz.common.base.view

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import com.ttxz.common.BaseApplication
import com.ttxz.common.base.viewmodel.BaseFragmentViewModel
import com.ttxz.common.base.viewmodel.BaseViewModel
import org.joor.Reflect
import java.lang.reflect.ParameterizedType

open class BaseFragment<VB : ViewBinding, VM : BaseFragmentViewModel<*>> : Fragment() {
    protected lateinit var viewBinding: VB
    protected lateinit var viewModel: VM
    private var mLoadingPopup: LoadingPopupView? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = createVB()
        createVM()
        registerDefaultUILiveData()
        registerUILiveData() //初使化和事件监听注册完成，VM可以执行数据相关的操作
        viewModel.initData()
        initCustomData()
        return view
    }

    /**
     * 注册LiveData事件，和VM通讯
     */
    open fun registerUILiveData() {
        //默认空实现
    }

    /**
     * 初使化完成VM和VB后，可以初使化相关元素和逻辑
     */
    open fun initCustomData() {
        //默认空实现
    }

    private fun createVB(): View {
        val viewClass: Class<*>
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            viewClass = type.actualTypeArguments[0] as Class<*>
            viewBinding = Reflect.onClass(viewClass).call("inflate", layoutInflater).get()
        }
        return viewBinding!!.root
    }

    /**
     * 创建ViewModel
     */
    private fun createVM() {
        val type = javaClass.genericSuperclass
        val modelClass = if (type is ParameterizedType) {
            type.actualTypeArguments[1] as Class<VM>
        } else { //如果没有指定泛型参数，则默认使用BaseViewModel
            BaseViewModel::class.java
        }
        viewModel =
            ViewModelProvider.AndroidViewModelFactory.getInstance(BaseApplication.Instance.mApplication)
                .create(modelClass) as VM //viewModel绑定View事件
        viewModel.let {
            lifecycle.addObserver(it)
        }
    }

    /**
     * 注册默认的通用LiveData事件
     */
    private fun registerDefaultUILiveData() {
        viewModel.showLoadingEvent.observeForever { aBoolean: Boolean ->
            if (aBoolean) {
                if (mLoadingPopup == null) {
                    mLoadingPopup = XPopup.Builder(context).asLoading("正在加载中")
                }
                mLoadingPopup?.show()
            } else {
                mLoadingPopup?.dismiss()
            }
        }
        viewModel.showToastEvent.observeForever { text: String? -> ToastUtils.show(text) }
    }
}